//导入Vue和Vue-router
import Vue from "vue";
import VueRouter from "vue-router";
import Find from "../components/Find.vue";
import My from "../components/My.vue"
import Part from "../components/Part.vue"
import Ranking from "../components/Ranking.vue"
import Recommend from "../components/Recommend.vue"
import SongList from "../components/SongList.vue"
//把VueRouter安装为Vue的插件
Vue.use(VueRouter)
//创建规则数组 数组里面路径为组件的映射对象
const routes = [{
        path: "/", // 默认hash值路径
        redirect: "/find" // 重定向到/find
        // 浏览器url中#后的路径被改变成/find-重新匹配数组规则
    },
    {
        path: "/find",
        name: "Find",
        component: Find,
        children: [{
                path: "recommend",
                component: Recommend
            },
            {
                path: "ranking",
                component: Ranking
            },
            {
                path: "songlist",
                component: SongList
            }
        ]
    },
    {
        path: "/my",
        component: My
    },
    {
        path: "/part",
        component: Part
    },
    {
        path: "/part/:username", // 有:的路径代表要接收具体的值
        component: Part
    },
]
//实例化router 实例对象
const router = new VueRouter({
    routes,
    mode: "history"
})
// 目标: 路由守卫
// 场景: 当你要对路由权限判断时
// 语法: router.beforeEach((to, from, next)=>{//路由跳转"之前"先执行这里, 决定是否跳转})
// 参数1: 要跳转到的路由 (路由对象信息)    目标
// 参数2: 从哪里跳转的路由 (路由对象信息)  来源
// 参数3: 函数体 - next()才会让路由正常的跳转切换, next(false)在原地停留, next("强制修改到另一个路由路径上")
// 注意: 如果不调用next, 页面留在原地

// 例子: 判断用户是否登录, 是否决定去"我的音乐"/my
const isLogin = false; // 登录状态(未登录)
router.beforeEach((to, from, next) => {
    if (to.path === "/my" && isLogin === false) {
        alert("请登录")
        next(false) // 阻止路由跳转
    } else {
        next() // 正常放行
    }
})

//向外共享router 对象
export default router